//
//  UITextField+ThemeExtension.swift
//  HeadlineNews
//
//  Created by han on 2019/7/26.
//  Copyright © 2019 han. All rights reserved.
//

import UIKit

extension UITextField {
    func updatePlaceholderAttributes(_ newAttributes: [NSAttributedString.Key: Any]) {
        guard let placeholder = self.attributedPlaceholder else { return }
        let newPlaceHolder = NSAttributedString(attributedString: placeholder, merging: newAttributes)
        self.attributedPlaceholder = newPlaceHolder
    }
}

extension UIRefreshControl {
    func updateTitleAttributes(_ newAttributes: [NSAttributedString.Key: Any]) {
        guard let title = self.attributedTitle else { return }
        let newString = NSAttributedString(attributedString: title,
                                           merging: newAttributes)
        self.attributedTitle = newString
    }
}

extension NSAttributedString {
    convenience init(attributedString: NSAttributedString, merging newAttributes: [NSAttributedString.Key: Any]) {
        let newString = NSMutableAttributedString(attributedString: attributedString)
        let range = NSMakeRange(0, attributedString.length)
        newString.enumerateAttributes(in: range, options: []) { (currentAttributes, range, _) in
            let mergedAttributes = currentAttributes.merge(with: newAttributes)
            newString.setAttributes(mergedAttributes, range: range)
        }
        self.init(attributedString: newString)
    }
}

private extension Dictionary {
    func merge(with dictionary: Dictionary) -> Dictionary{ // 去掉重复的key
        return dictionary.reduce(into: self, { (result, pair) in
            let (key, value) = pair
            result[key] = value
        })
    }
}
